package cn.lhf.cd.controller;

import cn.lhf.cd.FXApplication;
import cn.lhf.cd.Main;
import cn.lhf.cd.annotation.FXController;
import cn.lhf.cd.entity.Admin;
import cn.lhf.cd.entity.User;
import cn.lhf.cd.mapper.AdminMapper;
import cn.lhf.cd.mapper.UserMapper;
import cn.lhf.cd.utils.StringUtils;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.apache.ibatis.session.SqlSession;

import java.net.URL;
import java.util.*;

@FXController(path = "/ui/login.fxml")
public class LoginController implements Initializable {
    public ComboBox<String> userTypeCombo;
    public TextField loginNameField;
    public PasswordField passwordField;

    private final ArrayList<String> userTypeList = new ArrayList<>(Arrays.asList("普通用户", "管理员"));
    public Label typeTipLabel;
    public Label loginNameTipLabel;
    public Label passwordTipLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        userTypeCombo.setItems(FXCollections.observableList(userTypeList)); //填充下拉框
        userTypeCombo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            //自动填充用户，调试用
            if (newValue.equals("管理员")) {
                loginNameField.setText("root");
                passwordField.setText("root");
            } else {
                loginNameField.setText("wopy");
                passwordField.setText("123456");
            }
        });
        FXApplication.setTitle("XXXX电商平台");  //设置标题
    }

    public void onLogin(ActionEvent event) throws Exception {
        String type = userTypeCombo.getValue();
        if (StringUtils.isEmpty(type)) {
            sendTip(typeTipLabel, "请选择用户类型！");
            return;
        }
        String loginName = loginNameField.getText();
        if (StringUtils.isEmpty(loginName)) {
            sendTip(loginNameTipLabel, "请输入帐号！");
            return;
        } else if (!loginName.matches("^[a-zA-Z0-9_]+$")) {
            sendTip(loginNameTipLabel, "账号必须由数字字母下划线组成！");
            return;
        }
        String password = passwordField.getText();
        if (StringUtils.isEmpty(password)) {
            sendTip(passwordTipLabel, "密码不能为空！");
            return;
        }

        if (type.equals("普通用户")) {
            SqlSession sqlSession = Main.openSqlSession();
            User user = sqlSession.getMapper(UserMapper.class).login(loginName, password);
            sqlSession.close();
            if (user != null) {
                //普通用户登录成功
                clearTips();
                FXApplication.showView(UserHomeController.class, controller -> {
                    controller.setSelf(user);
                    controller.setContentFromSelf();
                    return null;
                });
                return;
            }
        } else if (type.equals("管理员")) {
            SqlSession sqlSession = Main.openSqlSession();
            Admin admin = sqlSession.getMapper(AdminMapper.class).login(loginName, password);
            sqlSession.close();
            if (admin != null) {
                //管理员登录成功
                clearTips();
                FXApplication.showView(AdminHomeController.class, null);
                return;
            }
        }
        sendTip(passwordTipLabel, "用户名或密码错误");
    }

    public void onCancel(ActionEvent event) {
        FXApplication.close();
        clearTips();
    }

    private static final Hashtable<Label, Timer> labelTimerHashtable = new Hashtable<>();

    /**
     * 发送提示
     * @param view 用于显示消息的文本标签
     * @param msg  要显示的消息
     */
    protected static synchronized void sendTip(Label view, String msg) {
        view.setText(msg);
        Timer timer;
        if (labelTimerHashtable.containsKey(view)) {
            timer = labelTimerHashtable.get(view);
            timer.cancel();                         //取消任务
            timer.purge();                          //销毁定时器
            labelTimerHashtable.remove(view);       //从任务表中删除任务
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> view.setText(null));    //不能直接在子线程中更新UI
                Timer thiz = labelTimerHashtable.get(view);
                thiz.cancel();
                thiz.purge();
                labelTimerHashtable.remove(view);
            }
        }, 15000);                                        //定时15秒
        labelTimerHashtable.put(view, timer);
    }

    /**
     * 清除所有提示
     */
    protected static void clearTips() {
        for (Label view:
                labelTimerHashtable.keySet()) {
            Timer timer = labelTimerHashtable.get(view);
            timer.cancel();
            timer.purge();
            view.setText(null);
        }
        labelTimerHashtable.clear();
    }
}
